package com.heqiang.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ResourceBundle;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class OssUtils {

	private static Logger logger = LoggerFactory.getLogger(OssUtils.class);

	@Value("${oss.key}")
	public static String KEY;
	@Value("${oss.secret}")
	public static String SECRET;
	@Value("${oss.end_point}")
	public static String END_POINT;
	@Value("${oss.bucket}")
	public static String BUCKET;
	@Value("${oss.region}")
	public static String REGION;
	@Value("${oss.img_folder}")
	public static String IMG_FOLDER;
	@Value("${oss.contract_folder}")
	public static String CONTRACT_FOLDER;
	@Value("${oss.file_folder}")
	public static String FILE_FOLDER;
	@Value("${oss.file_url}")
	public static String FILE_URL;
	@Value("${oss.img_url}")
	public static String IMG_URL;
	@Value("${oss.contract_url}")
	public static String CONTRACT_URL;

	public static OSSClient client;

	static {
		init();
	}

	public static void init() {
		if (null != client) {
			return ;
		}
		ResourceBundle rb = ResourceBundle.getBundle("application");
		KEY = rb.getString("oss.key").trim();
		SECRET = rb.getString("oss.secret").trim();
		END_POINT = rb.getString("oss.end_point").trim();
		BUCKET = rb.getString("oss.bucket").trim();
		REGION = rb.getString("oss.region").trim();
		IMG_FOLDER = rb.getString("oss.img_folder").trim();
		FILE_FOLDER = rb.getString("oss.file_folder").trim();
		CONTRACT_FOLDER = rb.getString("oss.contract_folder").trim();
		IMG_URL = rb.getString("oss.img_url").trim();
		FILE_URL = rb.getString("oss.file_url").trim();
		CONTRACT_URL = rb.getString("oss.contract_url").trim();
		client = new OSSClient(END_POINT, KEY, SECRET);
	}

	/**
	 * 上传文件
	 *
	 * @author felix  @date 2015-4-16 下午5:56:38
	 * @param file
	 * @param saveName
	 * @throws OSSException
	 * @throws ClientException
	 * @throws IOException
	 */
	public static String uploadFile(MultipartFile file,String saveName) throws OSSException, ClientException, IOException{
		saveName = IMG_FOLDER+saveName;
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(file.getSize());
		PutObjectResult result = client.putObject(BUCKET, saveName, file.getInputStream(), meta);
		return result.getETag();
	}

	/**
	 * 上传文件
	 *
	 * @author felix  @date 2015-4-16 下午5:56:38
	 * @param file
	 * @param saveName
	 * @throws OSSException
	 * @throws ClientException
	 * @throws IOException
	 */
	public static String uploadContarctFile(MultipartFile file,String saveName, String oriName) throws OSSException, ClientException, IOException{
		saveName = CONTRACT_FOLDER + saveName;
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(file.getSize());
		meta.setContentDisposition("attachment;filename=" + oriName);
		PutObjectResult result = client.putObject(BUCKET, saveName, file.getInputStream(), meta);
		logger.info("上传OSS的文件结果:result:{},\t 文件名:{}",JSON.toJSONString(result),saveName);
		return result.getETag();
	}

	/**
	 * 上传文件
	 *
	 * @author felix  @date 2015-4-16 下午5:56:38
	 * @param file
	 * @param saveName
	 * @return
	 * @throws OSSException
	 * @throws ClientException
	 * @throws IOException
	 */
	public static String uploadFile(File file, String saveName, boolean isImg) throws OSSException, ClientException, IOException{
//		 logger.info("上传OSS的文件名称:" + saveName);
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(file.length());
		meta.setContentDisposition("attachment;filename=" + file.getName().trim());
//		 logger.info("meta:{}",meta.getContentDisposition());
		PutObjectResult result = client.putObject(BUCKET, (isImg ? IMG_FOLDER : FILE_FOLDER)+saveName,  new FileInputStream(file), meta);
		logger.info("上传OSS的文件结果:result:{},\t 文件名:{}",JSON.toJSONString(result),saveName);
		return result.getETag();
	}

	/**
	 * 上传文件
	 * @author felix  @date 2015-4-16 下午5:56:38
	 * @param file
	 * @param saveName
	 * @return
	 * @throws OSSException
	 * @throws ClientException
	 * @throws IOException
	 */
	public static String uploadFile(MultipartFile file,String saveName,boolean isImg) throws OSSException, ClientException, IOException{
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(file.getSize());
		PutObjectResult result = client.putObject(BUCKET, (isImg ? IMG_FOLDER : FILE_FOLDER)+saveName, file.getInputStream(), meta);
		return result.getETag();
	}

	public static String uploadFile(InputStream inputStream, String saveName, boolean isImg) throws IOException {
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(inputStream.available());
		PutObjectResult result = client.putObject(BUCKET, (isImg ? IMG_FOLDER : FILE_FOLDER)+saveName, inputStream, meta);
		return result.getETag();
	}

	/**
	 * 上传文件
	 * @author linweiqin  @date 2015-4-16 下午5:56:38
	 * @param
	 * @param saveName
	 * @return
	 * @throws OSSException
	 * @throws ClientException
	 * @throws IOException
	 */
	public static String uploadFile(URL urlObj,String saveName) throws OSSException, ClientException, IOException{
		saveName = IMG_FOLDER + saveName;
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(urlObj.openStream().available());
		PutObjectResult result = client.putObject(BUCKET, saveName, urlObj.openStream(), meta);
		return result.getETag();
	}


	public static String uploadFile(String url)throws Exception{
		//String floder =  OssUtils.class.getResource("/").getPath() ;
		//线上
		String floder = "/home/png/";
		logger.info("url---------------"+url);
		String saveName = java.util.UUID.randomUUID().toString()+".jpg";
		downloadNet(url, floder + saveName);
		String wxcode = floder + saveName;

		File file = new File(wxcode);
		uploadFile(file,saveName, wxcode);
		file.deleteOnExit();
		return saveName;
	}

	public static String uploadFile(File file, String saveName, String name) throws OSSException, ClientException, IOException {
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentLength(file.length());
		String key = "attachment;filename="+name;
		key = key.replaceAll("null", "");
		meta.setContentDisposition(key);
		meta.setContentDisposition("attachment;filename=" + file.getName().trim());
		// 所有文件都放在file文件夹里面，不管是图片还是其他都放在这
		PutObjectResult result = client.putObject(BUCKET, IMG_FOLDER + saveName, new FileInputStream(file), meta);
		return result.getETag();
	}




	//下载图片
	public static void downloadNet(String str, String path) throws MalformedURLException {
		int byteSum = 0;
		int byteRead = 0;
		URL url = new URL(str);
		try {
			URLConnection conn = url.openConnection();
			InputStream inStream = conn.getInputStream();
			FileOutputStream fs = new FileOutputStream(path);
			byte[] buffer = new byte[1024];
			while ((byteRead = inStream.read(buffer)) != -1) {
				byteSum += byteRead;
				fs.write(buffer, 0, byteRead);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//网络路径转本地文件
	public static  File getFile(String imgUrl) {
		if (StringUtils.isBlank(imgUrl) || !imgUrl.startsWith("http")) {
			return new File(imgUrl);
		}
		// 生成图片名字和保存路径
		//String filePath = "d:/file/" + "wxcode.jpg";
		//String filePath = "/home/software/yz-fan/file/" + "wxcode.jpg";
		String filePath = "/home/png/" + "mediaId.jpg";
		// 先保存图片到本地
		saveImg(imgUrl, filePath);
		// 读取保存的文件
		File file = new File(filePath);
		return file;
	}


	protected static  void saveImg(String imgUrl, String filePath) {
		InputStream input = null;
		OutputStream os = null;
		try {
			URL url = new URL(imgUrl);
			URLConnection con = url.openConnection();
			// 得到URL的输入流
			input = con.getInputStream();
			// 设置数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流保存图片至本地
			os = new FileOutputStream(filePath);
			while ((len = input.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				os.close();
				input.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
